package com.yanboot.iot.utils;

import cn.hutool.core.date.DateUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Author fdj
 * @Date 2024/10/26 14:06
 * @Description 消防用传服务端
 */
@Slf4j
@Component
public class FireUserTransferServer {

    @Value("${fire.port:7902}")
    private int port;

    @PostConstruct
    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new HikUserTransferServerHandler());
                    }
                });

        // 绑定端口，但不调用sync()
        ChannelFuture f = b.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                log.info("消防上行平台服务端启动成功, 监听端口：{}", port);
            } else {
                log.error("端口绑定失败: {}", future.cause().getMessage(), future.cause());
            }
        });

        f.channel().closeFuture().addListener(future -> {
            log.info("服务器已关闭,时间：{}", DateUtil.now());
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        });
    }
}
